package com.yonyou.ucf.mdf.app.isvdxq.other.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductTempSKUEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.UnitEnity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ProductEntityBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.UnitassistEntityBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/basedata",DxqConfig.pre_pcUrl+"/basedata"})
public class BaseDataController {
    private static final Logger logger = LoggerFactory.getLogger(BaseDataController.class);

    @Autowired
    BaseService baseService;
    @Autowired
    ProductSKUService productSKUService;
    @Autowired
    ProductService productService;
    @Autowired
    ProductSKUTempService productSKUTempService;
    @Autowired
    UnitassistService unitassistService;
    @Autowired
    UnitService unitService;

    @RequestMapping("/GetProductList")
    public DataResult GetProductList(HttpServletRequest request) {
        DataResult result = new DataResult(1, "操作成功");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> reqParams = RequestTool.getParams(request);
            List<ProductEntity> productEntities = productService.SelectAll(tenantId);
            List<UnitEnity> unitEnities = unitService.SelectAll(tenantId);
            List<UnitassistEntityBean> unitassistEntities = unitassistService.SelectAll(tenantId);
            List<ProductEntityBean> dataList = new ArrayList<>();
            for (ProductEntity item : productEntities) {
                if(StringUtils.isEmpty(item.getDefaultSKUId())){
                    item.setDefaultSKUId(item.getId().toString());
                }
                ProductEntityBean entity = MyTool.convertBean2Bean(item, ProductEntityBean.class);
                entity.setRemark_dxq("");
                // 计量单位补全
                UnitEnity unitEnity = unitEnities.stream().filter(it -> it.getId() == Long.parseLong(entity.getUnit()))
                        .findFirst().orElse(null);
                if (unitEnity != null) {
                    entity.setUnitCode(unitEnity.getCode());
                    entity.setUnitName(unitEnity.getUnitName());
                } else {
                    UnitassistEntityBean tempEntity = unitassistEntities.stream()
                            .filter(it -> it.getAssistId() != null && it.getAssistId().equals(entity.getUnit()))
                            .findFirst().orElse(null);
                    if (tempEntity != null) {
                        entity.setUnitCode(tempEntity.getCode());
                        entity.setUnitName(tempEntity.getUnitName());
                    }
                }
                // 库存单位补全
                UnitEnity unitEnityStock = unitEnities.stream().filter(it -> it.getId() == Long.parseLong(entity.getStockUnit()))
                        .findFirst().orElse(null);
                if (unitEnityStock != null) {
                    entity.setStockUnitCode(unitEnityStock.getCode());
                    entity.setStockUnitName(unitEnityStock.getUnitName());
                } else {
                    UnitassistEntityBean tempEntity = unitassistEntities.stream()
                            .filter(it -> it.getAssistId() != null && it.getAssistId().equals(entity.getStockUnit()))
                            .findFirst().orElse(null);
                    if (tempEntity != null) {
                        entity.setUnitCode(tempEntity.getCode());
                        entity.setUnitName(tempEntity.getUnitName());
                    }
                }
                dataList.add(entity);
            }
            result.setDataList(dataList);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
            System.out.println(JSONObject.toJSONString(result));
        }
        return result;
    }

    @RequestMapping("/GetProductskuList")
    public DataResult GetProductskuList(HttpServletRequest request) {
        DataResult result = new DataResult(1, "操作成功");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> reqParams = RequestTool.getParams(request);
            List<String> productIds = (List<String>) reqParams.get("productIds");
            Long[] ids = productIds.toArray(new Long[productIds.size()]);
            List<ProductTempSKUEntity> dataList = productSKUTempService.SelectAllByProductIds(ids, tenantId);
            result.setDataList(dataList);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
            System.out.println(JSONObject.toJSONString(result));
        }
        return result;
    }

    /**
     * 档案主物料信息 + 辅助物料信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/GetProductunitList")
    public DataResult GetProductunitList(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> reqParams = RequestTool.getParams(request);
            String unitId = reqParams.get("unitId");
            String proId = reqParams.get("productId");
            UnitEnity unitEnity = unitService.SelectById(Long.valueOf(unitId));
            UnitassistEntityBean unitassistEntityBean = new UnitassistEntityBean();
            unitassistEntityBean.setAssistUnit(String.valueOf(unitEnity.getId()));
            unitassistEntityBean.setAssistUnit_Name(unitEnity.getUnitName());
            unitassistEntityBean.setAssistUnitCount(String.valueOf(1));
            if (unitEnity.getConvertCoefficient()!=null) {
                unitassistEntityBean.setMainUnitCount(String.valueOf(unitEnity.getConvertCoefficient()));
            }
            unitassistEntityBean.setProductId(proId);
            unitassistEntityBean.setPubts(unitEnity.getPubts());
            unitassistEntityBean.setTenantId(unitEnity.getTenantId());
            unitassistEntityBean.setUnitExchangeType("0");
            List<UnitassistEntityBean> unitassistEntityBeans = unitassistService.SelectByProId(proId, tenantId);
            unitassistEntityBeans.add(unitassistEntityBean);
            result = new DataResult(1, "操作成功");
            result.setDataListEx(unitassistEntityBeans);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 主物料信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/GetUnitList")
    public DataResult GetUnitList(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> reqParams = RequestTool.getParams(request);
            List<UnitEnity> unitEnities = unitService.SelectAll(tenantId);
            result = new DataResult(1, "操作成功");
            result.setDataListEx(unitEnities);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }
}
